<template>
  <div class="system-configuration-page art-full-height">
    <ElCard class="art-table-card fixed-header-card" shadow="never">
      <template #header>
        <div class="card-header fixed-header">
          <span class="title">系统配置</span>
          <ElButton type="primary" @click="handleSave" :loading="saveLoading" v-ripple>
            保存配置
          </ElButton>
        </div>
      </template>

      <div class="scrollable-content">
        <ElForm
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="200px"
          label-position="left"
          v-loading="loading"
        >
        <div class="form-section">
          <div class="section-title">扫码相关配置</div>
          <ElFormItem label="重复扫码不计入时间" prop="sysMinAreaTime">
            <ElInputNumber
              v-model="formData.sysMinAreaTime"
              :min="0"
              :step="1"
              placeholder="请输入分钟数"
            />
            <span class="unit-text">分钟</span>
          </ElFormItem>

          <ElFormItem label="最远扫码距离" prop="sysMaxAreaDistance">
            <ElInputNumber
              v-model="formData.sysMaxAreaDistance"
              :min="0"
              :step="1"
              :precision="0"
              placeholder="请输入米数"
            />
            <span class="unit-text">米</span>
          </ElFormItem>
        </div>

        <div class="form-section">
          <div class="section-title">距离相关配置</div>
          <ElFormItem label="附近小区" prop="sysNearArea">
            <ElInputNumber
              v-model="formData.sysNearArea"
              :min="0"
              :step="1"
              :precision="0"
              placeholder="请输入米数"
            />
            <span class="unit-text">米</span>
          </ElFormItem>

          <ElFormItem label="附近驿站" prop="sysNearRest">
            <ElInputNumber
              v-model="formData.sysNearRest"
              :min="0"
              :step="1"
              :precision="0"
              placeholder="请输入米数"
            />
            <span class="unit-text">米</span>
          </ElFormItem>
        </div>

        <div class="form-section">
          <div class="section-title">信息核实配置</div>
          <ElFormItem label="信息核实-需核验" prop="sysInfoCheckTime">
            <ElInputNumber
              v-model="formData.sysInfoCheckTime"
              :min="0"
              :step="1"
              placeholder="请输入天数"
            />
            <span class="unit-text">天</span>
          </ElFormItem>

          <ElFormItem label="信息核实-异常" prop="sysInfoErrorTime">
            <ElInputNumber
              v-model="formData.sysInfoErrorTime"
              :min="0"
              :step="1"
              placeholder="请输入天数"
            />
            <span class="unit-text">天</span>
          </ElFormItem>
        </div>

        <div class="form-section">
          <div class="section-title">商品配置</div>
          <ElFormItem label="自动收货时间" prop="sysGoodsAuthConfirm">
            <ElInputNumber
              v-model="formData.sysGoodsAuthConfirm"
              :min="0"
              :step="1"
              placeholder="请输入天数"
            />
            <span class="unit-text">天</span>
          </ElFormItem>
        </div>

        <div class="form-section">
          <div class="section-title">报事通知配置</div>
          <ElFormItem label="报事未处理通知时间" prop="sysIssueInformTime">
            <ElInputNumber
              v-model="formData.sysIssueInformTime"
              :min="0"
              :step="1"
              placeholder="请输入分钟数"
            />
            <span class="unit-text">分钟</span>
          </ElFormItem>

          <ElFormItem label="报事未处理通知人员" prop="sysIssueInformEmployeeList">
            <ArtEmployeeSelect
              v-model="formData.sysIssueInformEmployeeList"
              multiple
              :page-size="10"
              :only-enabled="true"
              :show-login-name="true"
              placeholder="请选择报事未处理通知人员"
              style="width: 400px"
            />
          </ElFormItem>
        </div>
      </ElForm>
      </div>
    </ElCard>
  </div>
</template>

<script setup lang="ts">
  import { ElMessage, ElCard, ElForm, FormInstance, FormRules } from 'element-plus'
  import request from '@/utils/http'
  import type { SysSettingVo, SysSettingBo } from '@/api/types'
  import ArtEmployeeSelect from '@/components/core/forms/art-employee-select/index.vue'

  defineOptions({ name: 'SystemConfiguration' })

  const formRef = ref<FormInstance>()
  const loading = ref(false)
  const saveLoading = ref(false)

   const formData = reactive({
    id: 0,
    sysMinAreaTime: 0,
    sysMaxAreaDistance: 0,
    sysNearArea: 0,
    sysNearRest: 0,
    sysInfoCheckTime: 0,
    sysInfoErrorTime: 0,
    sysGoodsAuthConfirm: 0,
    sysIssueInformTime: 0,
    sysIssueInformEmployeeList: [] as number[],
    sysTaskSignDistance: 0
  })

const formRules: FormRules = {
    sysMinAreaTime: [
      { required: true, message: '请输入重复扫码不计入时间', trigger: 'blur' },
      { type: 'number', min: 0,  message: '请输入数值', trigger: 'blur' }
    ],
    sysMaxAreaDistance: [
      { required: true, message: '请输入最远扫码距离', trigger: 'blur' },
      { type: 'number', min: 0, message: '请输入数值', trigger: 'blur' }
    ],
    sysNearArea: [
      { required: true, message: '请输入附近小区距离', trigger: 'blur' },
      { type: 'number', min: 0, message: '请输入数值', trigger: 'blur' }
    ],
    sysNearRest: [
      { required: true, message: '请输入附近驿站距离', trigger: 'blur' },
      { type: 'number', min: 0, message: '请输入数值', trigger: 'blur' }
    ],
    sysInfoCheckTime: [
      { required: true, message: '请输入信息核实-需核验天数', trigger: 'blur' },
      { type: 'number', min: 0,  message: '请输入数值', trigger: 'blur' }
    ],
    sysInfoErrorTime: [
      { required: true, message: '请输入信息核实-异常天数', trigger: 'blur' },
      { type: 'number', min: 0,  message: '请输入数值', trigger: 'blur' }
    ],
    sysGoodsAuthConfirm: [
      { required: true, message: '请输入自动收货时间', trigger: 'blur' },
      { type: 'number', min: 0,  message: '请输入数值', trigger: 'blur' }
    ],
    sysIssueInformTime: [
      { required: true, message: '请输入报事未处理通知时间', trigger: 'blur' },
      { type: 'number', min: 0,  message: '请输入数值', trigger: 'blur' }
    ],
    sysIssueInformEmployeeList: [
      { required: true, message: '请选择报事未处理通知人员', trigger: 'change' }
    ]
  }
const getConfigData = async () => {
  loading.value = true
  try {
    const res = await request<any>('/sys/setting/getData', {
      method: 'POST'
    })
    
    const data = res as SysSettingVo
    formData.id = (data.id !== undefined && data.id !== null) ? data.id : 0
    formData.sysMinAreaTime = (data.sysMinAreaTime !== undefined && data.sysMinAreaTime !== null) ? data.sysMinAreaTime : 0
    formData.sysMaxAreaDistance = (data.sysMaxAreaDistance !== undefined && data.sysMaxAreaDistance !== null) ? data.sysMaxAreaDistance : 0
    formData.sysNearArea = (data.sysNearArea !== undefined && data.sysNearArea !== null) ? data.sysNearArea : 0
    formData.sysNearRest = (data.sysNearRest !== undefined && data.sysNearRest !== null) ? data.sysNearRest : 0
    formData.sysInfoCheckTime = (data.sysInfoCheckTime !== undefined && data.sysInfoCheckTime !== null) ? data.sysInfoCheckTime : 0
    formData.sysInfoErrorTime = (data.sysInfoErrorTime !== undefined && data.sysInfoErrorTime !== null) ? data.sysInfoErrorTime : 0
    formData.sysGoodsAuthConfirm = (data.sysGoodsAuthConfirm !== undefined && data.sysGoodsAuthConfirm !== null) ? data.sysGoodsAuthConfirm : 0
    formData.sysIssueInformTime = (data.sysIssueInformTime !== undefined && data.sysIssueInformTime !== null) ? data.sysIssueInformTime : 0
    formData.sysIssueInformEmployeeList = data.sysIssueInformEmployeeList 
      ? data.sysIssueInformEmployeeList.map(employee => employee.id ?? 0).filter(id => id !== 0)
      : []
  } catch (error) {
    console.error('获取系统配置失败:', error)
    ElMessage.error('获取系统配置失败')
  } finally {
    loading.value = false
  }
}

  const handleSave = async () => {
    if (!formRef.value) return

    try {
      await formRef.value.validate()

      saveLoading.value = true

      const submitData = {
        id: formData.id !== undefined ? Number(formData.id) : 0,
        sysMinAreaTime: formData.sysMinAreaTime !== undefined ? Number(formData.sysMinAreaTime) : 0,
        sysMaxAreaDistance: formData.sysMaxAreaDistance !== undefined ? Number(formData.sysMaxAreaDistance) : 0,
        sysNearArea: formData.sysNearArea !== undefined ? Number(formData.sysNearArea) : 0,
        sysNearRest: formData.sysNearRest !== undefined ? Number(formData.sysNearRest) : 0,
        sysInfoCheckTime: formData.sysInfoCheckTime !== undefined ? Number(formData.sysInfoCheckTime) : 0,
        sysInfoErrorTime: formData.sysInfoErrorTime !== undefined ? Number(formData.sysInfoErrorTime) : 0,
        sysGoodsAuthConfirm: formData.sysGoodsAuthConfirm !== undefined ? Number(formData.sysGoodsAuthConfirm) : 0,
        sysIssueInformTime: formData.sysIssueInformTime !== undefined ? Number(formData.sysIssueInformTime) : 0,
        sysIssueInformEmployeeList: Array.isArray(formData.sysIssueInformEmployeeList) 
          ? formData.sysIssueInformEmployeeList.map(id => Number(id)).filter(id => !isNaN(id))
          : [],
        sysTaskSignDistance: formData.sysTaskSignDistance !== undefined ? Number(formData.sysTaskSignDistance) : 0
};
      const res = await request<{ code: number; msg: string; data: boolean }>('/sys/setting/updateData', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        data: submitData
      })

      ElMessage.success('保存成功')
      await getConfigData()
    } catch (error: any) {
      if (error !== false) {
        console.error('保存配置失败:', error)
        ElMessage.error('保存配置失败: ' + (error.msg || error.message || '未知错误'))
      }
    } finally {
      saveLoading.value = false
    }
  }


onMounted(async () => {
  await getConfigData()
})
</script>

<style lang="scss" scoped>
  .system-configuration-page {
    padding-bottom: 15px;

    .art-table-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .title {
          font-weight: 600;
          font-size: 16px;
          color: var(--el-text-color-primary);
        }
      }

      .scrollable-content {
        max-height: calc(100vh - 200px);
        overflow-y: auto;
        padding: 20px 0;

        // 自定义滚动条样式
        &::-webkit-scrollbar {
          width: 6px;
        }

        &::-webkit-scrollbar-thumb {
          background-color: var(--art-gray-400);
          border-radius: 3px;

          &:hover {
            background-color: var(--art-gray-500);
          }
        }

        &::-webkit-scrollbar-track {
          background-color: transparent;
        }
      }
    }

    // 表单分组样式
    .form-section {
      margin-bottom: 32px;
      padding-bottom: 24px;
      border-bottom: 1px solid var(--art-border-color);

      &:last-child {
        border-bottom: none;
        margin-bottom: 0;
      }

      .section-title {
        font-size: 15px;
        font-weight: 600;
        color: var(--el-text-color-primary);
        margin-bottom: 20px;
        padding-left: 12px;
        border-left: 3px solid rgb(var(--art-primary));
        display: flex;
        align-items: center;
        min-height: 24px;
      }
    }

    // 表单项样式
    :deep(.el-form-item) {
      margin-bottom: 24px;

      .el-form-item__label {
        color: var(--el-text-color-regular);
        font-weight: 500;
      }

      .el-input-number {
        width: 200px;
      }

      .unit-text {
        margin-left: 12px;
        color: var(--el-text-color-secondary);
        font-size: 14px;
      }

      // 多选框样式
      .el-select {
        .el-select__tags {
          max-height: 100px;
          overflow-y: auto;

          &::-webkit-scrollbar {
            width: 4px;
          }

          &::-webkit-scrollbar-thumb {
            background-color: var(--art-gray-400);
            border-radius: 2px;
          }
        }
      }
    }

    // Loading 状态样式
    :deep(.el-loading-mask) {
      background-color: rgba(var(--art-gray-100-rgb), 0.8);
    }


  }
</style>